<script lang="ts" setup>
import { ref, onUnmounted } from 'vue';
import { message,Input, } from 'ant-design-vue';
import { useVbenModal, VbenButton } from '@vben/common-ui';

// WebSocket 状态类型
type WsStatus = 'disconnected' | 'connecting' | 'connected' | 'error';

// 响应式数据
const wsUrl = ref(`wss://shenluwei.cn/ws/`);

// const wsUrl = '/ws';
// const wsUrl = ref(import.meta.env.VITE_WS_URL);
const inputMessage = ref('');
const messageLog = ref<Array<{ time: string; type: string; content: string }>>([]);
const status = ref<WsStatus>('disconnected');
const socket = ref<WebSocket | null>(null);

// 状态样式映射
const statusClasses = {
  disconnected: 'status closed',
  connecting: 'status connecting',
  connected: 'status open',
  error: 'status closed'
};

// 状态文本映射
const statusTexts = {
  disconnected: '未连接',
  connecting: '连接中...',
  connected: '已连接',
  error: '连接错误'
};

// 添加消息到日志
const addMessage = (content: string, type: string = 'info') => {
  const now = new Date();
  messageLog.value.push({
    time: now.toLocaleTimeString(),
    type,
    content
  });
};

// 连接 WebSocket
const connect = () => {
  status.value = 'connecting';
  addMessage(`正在连接到 ${wsUrl.value}`, 'system');
  
  try {
    socket.value = new WebSocket(wsUrl.value);
    
    socket.value.onopen = () => {
      status.value = 'connected';
      addMessage('连接已建立', 'success');
      message.success('WebSocket 连接成功！');
    };
    
    socket.value.onmessage = (event) => {
      let receivedData = event.data;
      // 处理二进制数据
      if (event.data instanceof Blob) {
        const reader = new FileReader();
        reader.onload = () => {
          addMessage(reader.result as string, 'received');
        };
        reader.readAsText(event.data);
      } else {
        addMessage(receivedData, 'received');
      }
    };
    
    socket.value.onclose = (event) => {
      if (event.wasClean) {
        addMessage(`连接已关闭，代码=${event.code} 原因=${event.reason}`, 'system');
        message.info('WebSocket 连接已关闭');
      } else {
        addMessage('连接中断', 'error');
        message.error('WebSocket 连接异常中断');
      }
      status.value = 'disconnected';
    };
    
    socket.value.onerror = () => {
      addMessage('WebSocket 错误: 请检查服务器是否运行且 Nginx 配置正确', 'error');
      status.value = 'error';
      message.error('WebSocket 连接错误');
    };
  } catch (error) {
    status.value = 'error';
    addMessage(`连接失败: ${error}`, 'error');
    message.error('WebSocket 连接失败');
  }
};

// 断开连接
const disconnect = () => {
  if (socket.value) {
    addMessage('正在关闭连接...', 'system');
    socket.value.close();
  }
};

//  发送消息
const sendMessage = () => {
  if (!inputMessage.value.trim()) {
    message.warning('请输入要发送的消息');
    return;
  }
  
  if (socket.value && socket.value.readyState === WebSocket.OPEN) {
    socket.value.send(inputMessage.value);
    addMessage(inputMessage.value, 'sent');
    inputMessage.value = '';
  } else {
    message.error('WebSocket 未连接');
  }
};

// 处理键盘回车事件
const handleKeyPress = (e: KeyboardEvent) => {
  if (e.key === 'Enter') {
    sendMessage();
  }
};

// 组件卸载时关闭连接
onUnmounted(() => {
  if (socket.value) {
    socket.value.close();
  }
});
</script>

<template>
  <div class="websocket-container">
    <h1>WebSocket 测试客户端</h1>
    <p>连接到: <strong>{{ wsUrl }}</strong></p>
    
    <div :class="statusClasses[status]">{{ statusTexts[status] }}</div>
    
    <div class="output">
      <div v-for="(msg, index) in messageLog" :key="index" class="message-item">
        <strong>[{{ msg.time }}] {{ msg.type }}:</strong> {{ msg.content }}
      </div>
    </div>
    
    <div class="input-group">
      <Input
        v-model:value="inputMessage"
        placeholder="输入要发送的消息"
        @keypress="handleKeyPress"
        class="message-input"
      />
      <VbenButton 
        type="primary" 
        @click="sendMessage" 
        :disabled="status !== 'connected'"
        class="action-btn"
      >
        发送
      </VbenButton>
      <VbenButton 
        @click="connect" 
        :disabled="status === 'connecting' || status === 'connected'"
        class="action-btn"
      >
        连接
      </VbenButton>
      <VbenButton 
        danger 
        @click="disconnect" 
        :disabled="status !== 'connected'"
        class="action-btn"
      >
        断开
      </VbenButton>
    </div>
  </div>
</template>

<style scoped>
.websocket-container {
  max-width: 800px;
  padding: 20px;
  margin: 0 auto;
  font-family: Arial, sans-serif;
}

.output {
  height: 300px;
  padding: 10px;
  margin-bottom: 10px;
  overflow-y: auto;
  background-color: #f9f9f9;
  border: 1px solid #ccc;
}

.message-item {
  margin-bottom: 5px;
}

.input-group {
  display: flex;
  gap: 10px;
  align-items: center;
}

.message-input {
  flex-grow: 1;
}

.action-btn {
  min-width: 80px;
}

.status {
  padding: 8px;
  margin: 10px 0;
  border-radius: 4px;
}

.connecting {
  background-color: #FFF3CD;
}

.open {
  background-color: #D4EDDA;
}

.closed {
  background-color: #F8D7DA;
}

</style>
